App.controller("accountManagementCtrl",function($scope, $rootScope, $location, $http, $compile, $stateParams, $timeout, path, publicService) {
	
	$scope.search = {};
	
	$scope.userLevel_show = true;		//商户级别（显示）
	$scope.accountUpOrDown_show = true;	//上下架（显示）
	$scope.userLabel_show = true;		//商户标签（显示）
	
	$scope.createAccount_show = true;		//创建账号（显示）
	
	
	$scope.creater_hidden = false;		//创建者（隐藏）
	$scope.userLevel_hidden = false;		//商户级别（隐藏）
	$scope.userLabel_hidden = false;		//商户标签（隐藏）
	$scope.upOrDown_hidden = false;		//上下架（隐藏）
	
	$scope.userLevelForWindow_show = true;	//商户级别弹框（显示）
	
	var alertModel = {};	//alert模态框
	
	
	
	if(userInfo.user_level==0){	//开发者
		publicService.initUserLevel("userLevel");			//初始化【用户级别】
		publicService.initUserLevel("userLevel_window");	//初始化【用户级别】
	}else if(userInfo.user_level==3){	//三级用户
		$scope.accountUpOrDown_show = false;
		
		$scope.upOrDown_hidden = true;
		
		publicService.initUserLevel_2("userLevel");			//初始化【用户级别】二级
		$scope.userLevelForWindow_show = false;
	}else if(userInfo.user_level==2){	//二级用户
		$scope.userLevel_show = false;
		$scope.userLabel_show = false;
		
		$scope.creater_hidden = true;
		$scope.userLevel_hidden = true;		
		$scope.userLabel_hidden = true;		
		
		$scope.userLevelForWindow_show = false;
		
		publicService.initUserLevel_2("userLevel");
	}else if(userInfo.user_level==1){	//一级用户
		$scope.createAccount_show = false;
	}
	
	
	
	//表格对象
	$scope.gridOptions = {
			dataSource : {
				transport : {
					read : {
						url : path+"/server/queryuserlist",
						type : 'POST',
						dataType : "json",
						contentType : "application/json"
					},
					parameterMap : function(options, operation) {
						if (operation == "read") {
							var sort = [{dir:"desc",field:"create_time"}];
							if(options.sort!=null && options.sort.length>0 ){
								if(options.sort[0].field=="createTime"){
									options.sort[0].field="create_time";
								}else{
									options.sort[0].field="create_time";
								}
								
								sort=options.sort;
							}
							
							var parameter = {
								page : options.page, //当前页
								pageSize : options.pageSize,
								param:{
									name: $scope.search.shopName,		//商户名称
									account: $scope.search.account,		//账号名称
									principal: $scope.search.principal,		//负责人
									
									phone_num: $scope.search.phone_num,		//商户名称
									user_level: $("#userLevel").data("kendoDropDownList").value(),		//商户级别
									state: $("#accountState").data("kendoDropDownList").value(),		//账号状态
									
									up_down: $("#accountUpOrDown").data("kendoDropDownList").value(),		//上下架
									tag: $scope.search.tag,		//商户标签
									start_create_time: $("#startTime").val(),		//商户名称
									end_create_time: $("#endTime").val(),		//商户名称
									sort:sort
								}
							};
							console.log('查询参数',parameter);
							return kendo.stringify(parameter);
						}
					},
				},
				pageSize : 10,
				serverPaging : true,
				serverSorting: true,
				schema : {
					data : function(d) {
						return d.data;
					},
					total : function(d) {
						return d.total; //总条数
					}
				},
			},
			pageable : {  //分页
				pageSizes: [10, 20, 50, 100],  //每页显示记录数
			  },  
			sortable: {   //排序
				//allowUnsort: false,  //允许无序
			    mode: "single"     //排序模式：single，multiple
			  },
			editable: false,  //true：单个编辑；popup：弹出新页面编辑
			dataBound: function () {   //序号
		        var rows = this.items();
		        var page = this.pager.page() - 1;
		        var pagesize = this.pager.pageSize();
		        $(rows).each(function () {
		            var index = $(this).index() + 1 + page * pagesize;
		            var rowLabel = $(this).find(".row-number");
		            $(rowLabel).html(index);
		        });
		    },
			columns : [
					{    
						title : "序号",
						field : "id", 
						width : "50px",
						template:"<input type='checkbox' class='recordClass' value='#: id #' />"+"<span class='row-number subTitle'></span>"
					},
					{
						field : "creater",         
						title : "创建者",     
						width : "100px",
						hidden: $scope.creater_hidden
					},
					{
						field : "name",         
						title : "属性名称",     
						width : "100px"
					},
					{
						field : "user_level",         
						title : "属性级别",     
						width : "100px",
						hidden: $scope.userLevel_hidden,
						values: [
						         { text: "一级", value: 1 },
						         { text: "二级", value: 2 },
						         { text: "三级", value: 3 }
				        ],
					},
//					{
//						field : "tag",         
//						title : "属性标签",     
//						width : "100px",
//						hidden: $scope.userLabel_hidden
//					},
					{
						field : "account",         
						title : "账号名称",     
						width : "100px"
					},
					{
						field : "principal",         
						title : "负责人",     
						width : "100px"
					},
					{
						field : "phone_num",         
						title : "联系方式",     
						width : "100px"
					},
					{
						field : "create_time",         
						title : "创建时间",     
						width : "100px"
					},
					{
						field : "update_time",         
						title : "修改时间",     
						width : "100px"
					},
					{
						field : "state",         
						title : "状态",     
						width : "100px",
						values: [
						         { text: "关闭", value: 0 },
						         { text: "正常", value: 1 }
				        ],
					},
					{
						field : "up_down",         
						title : "上下架",     
						width : "100px",
						hidden: $scope.upOrDown_hidden,
						values: [
						         { text: "下架", value: 0 },
						         { text: "上架", value: 1 }
				        ],
					},
					{
						field : "id",         
						title : "操作",     
						width : "100px",
						template: function(e){
					    	var html = '';
					    	
					    	if(userInfo.user_level==0){	//开发者
					    		if(e.is_creater==1){
					    			html += '<div class="width_3 operation" ng-click="editUser('+e.id+',true,'+e.user_level+')">编辑</div>';
					    		}else{
					    			html += '<div class="width_3 operation" ng-click="editUser('+e.id+',false,'+e.user_level+')">编辑</div>';
					    		}
					    		if(e.state==0){
					    			html += '<div class="width_3 operation" ng-click="updateUser(1,'+e.id+',1)">开通</div>';
					    		}else if(e.state==1){
					    			html += '<div class="width_3 operation" ng-click="updateUser(1,'+e.id+',0)">关闭</div>';
					    		}
					    		if(e.is_creater==1 && e.user_level==1){
					    			if(e.up_down==0){
						    			html += '<div class="width_3 operation" ng-click="updateUser(2,'+e.id+',1)">上架</div>';
						    		}else if(e.up_down==1){
						    			html += '<div class="width_3 operation" ng-click="updateUser(2,'+e.id+',0)">下架</div>';
						    		}
					    		}
					    	}else if(userInfo.user_level==3){	//三级用户
					    		if(e.is_creater==1){
					    			html += '<div class="width_3 operation" ng-click="editUser('+e.id+',true,'+e.user_level+')">编辑</div>';
						    		if(e.state==0){
						    			html += '<div class="width_3 operation" ng-click="updateUser(1,'+e.id+',1)">开通</div>';
						    		}else if(e.state==1){
						    			html += '<div class="width_3 operation" ng-click="updateUser(1,'+e.id+',0)">关闭</div>';
						    		}
						    		if(e.user_level==1){
						    			if(e.up_down==0){
							    			html += '<div class="width_3 operation" ng-click="updateUser(2,'+e.id+',1)">上架</div>';
							    		}else if(e.up_down==1){
							    			html += '<div class="width_3 operation" ng-click="updateUser(2,'+e.id+',0)">下架</div>';
							    		}
						    		}
					    		}else{
					    			html += '<div class="width_3 operation" ng-click="lookUser('+e.id+')">查看</div>';
					    		}
					    	}else if(userInfo.user_level==2){	//二级用户
					    		html += '<div class="width_3 operation" ng-click="editUser('+e.id+',true,'+e.user_level+')">编辑</div>';
					    		if(e.state==0){
					    			html += '<div class="width_3 operation" ng-click="updateUser(1,'+e.id+',1)">开通</div>';
					    		}else if(e.state==1){
					    			html += '<div class="width_3 operation" ng-click="updateUser(1,'+e.id+',0)">关闭</div>';
					    		}
					    		if(e.up_down==0){
					    			html += '<div class="width_3 operation" ng-click="updateUser(2,'+e.id+',1)">上架</div>';
					    		}else if(e.up_down==1){
					    			html += '<div class="width_3 operation" ng-click="updateUser(2,'+e.id+',0)">下架</div>';
					    		}
					    	}else if(userInfo.user_level==1){	//一级用户
					    		
					    	}
					    	
					    	return html;
					    },
					}
			]
	};
	
	//查询
	$scope.search = function(){
		$scope.grid.dataSource.page(1);
	}
	
	//全选，取消
	$scope.chooseAll = function(className,flag){
		publicService.chooseAllByClassName(className,flag);
	}
	
	//导出表格数据（1：筛选导出，2：选中导出）  
	$scope.downloadTableData = function(type){
		var paramObj = {};
		
		if(type==1){	//筛选导出
			paramObj = {
					page : 1, 
					pageSize : 10,
					ispage:false,
					param:{
						name: $scope.search.shopName,		//商户名称
						account: $scope.search.account,		//账号名称
						principal: $scope.search.principal,		//负责人
						
						phone_num: $scope.search.phone_num,		//商户名称
						user_level: $("#userLevel").data("kendoDropDownList").value(),		//商户级别
						state: $("#accountState").data("kendoDropDownList").value(),		//账号状态
						
						up_down: $("#accountUpOrDown").data("kendoDropDownList").value(),		//上下架
						tag: $scope.search.tag,		//商户标签
						start_create_time: $("#startTime").val(),		//商户名称
						end_create_time: $("#endTime").val(),		//商户名称
					}
			};
		}else if(type==2){	//选中导出
			var ids = publicService.getChooseValueByClassName("recordClass");
			if(ids.length==0){
				$scope.alertMessage("请选择商户！");
				return;
			}
			
			paramObj = {
					page : 1, 
					pageSize : 10,
					param:{
						ids: ids
					}
			};
		}

		var requestUrl = path+"/server/export";		//请求路径
		var exportModule = "user_module";			//模块名称
		var form = $("<form method='POST' action='"+requestUrl+"' target='_self'>"
						+"<input type='hidden' name='module_code' value='"+exportModule+"'/>"
						+"<input type='hidden' name='page' value='"+angular.toJson(paramObj)+"'/>"
					+"</form>");
		console.log("【表单参数】",form.serializeArray());
	    $(document.body).append(form);
	    form.submit();	
	}
	
	//提示信息
	$scope.alertMessage = function(message){
		alertModel.pannel = jqueryAlert({
			content: message,
			modal: true
		});
	}
	
	//创建账号
	$scope.addUser = function(){
		if(userInfo.user_level==0){	//开发者
			$scope.userWindow.center().open();   //打开弹框
		}else{
			$scope.createUser();
		}
	}
	
	//创建商户
	$scope.createUser = function(){
		var userLevel = "";		//用户级别
		var userLabel = "";		//用户标签
		
		if(userInfo.user_level==0){	//开发者
			userLevel = $("#userLevel_window").data("kendoDropDownList").value();
			if(!userLevel){
				$scope.alertMessage("请选择【属性级别】！");
				return;
			}
		}else if(userInfo.user_level==3){	//三级用户
			userLevel = 2;
		}else if(userInfo.user_level==2){	//二级用户
			userLevel = 1;
		}else if(userInfo.user_level==1){	//一级用户
			
		}
		if(userLevel==3){
			userLabel = "集团";
		}else if(userLevel==2){
			userLabel = "分公司";
		}else if(userLevel==1){
			userLabel = "专卖店";
		}
		
		var params = {
			method:"add",
			userLevel: userLevel,
			userLabel: userLabel
		};
		$location.path("/addCount/"+angular.toJson(params));
	}
	
	//编辑商户
	$scope.editUser = function(id,isEditPermission,level){
		var params = {
				method:"edit",
				id: id,
				editPremission: isEditPermission,
				userLevel: level
			};
		$location.path("/addCount/"+angular.toJson(params));
	}
	
	//查看商户
	$scope.lookUser = function(id){
		var params = {
				method:"look",
				id: id
			};
		$location.path("/addCount/"+angular.toJson(params));
	}
	
	//更新商户
	$scope.updateUser = function(type,id,flag){	//type:1(开通，关闭) type:2(上下架)
		alertModel.confirm = jqueryAlert({
			content: "确定？",
			modal: true,
			width: "300",
			"buttons" :{
				"确定" : function(){
					alertModel.confirm.close();

					$http({
						   url: path+'/server/update/'+type+'/'+id+'/'+flag,
						   method: 'GET'
					}).success(function(data){
						if(data.code==0){
							$scope.alertMessage("成功！");
							$scope.search();
						}else{
							$scope.alertMessage("失败！");
						}
					}).error(function(data){
						alert(data);   
					})
				},
				"取消" : function(){
					alertModel.confirm.close();
				}
			}
		});
	}
	
	
	publicService.initAccountState("accountState");			//初始化【账号状态】
	publicService.initAccountUpOrDown("accountUpOrDown");	//初始化【账号上下架】
	publicService.initDate("startTime");	//创建时间（始）
	publicService.initDate("endTime");		//创建时间（止）
	

	
	
	
	
	
	
	
});